﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using System.Data;
using Eneta.Portal.Common.Dto;

namespace Eneta.Portal.Controls
{
    public class TagsViewControl : UserControl
    {
        private int _tagCount;

        public SPListItem Item
        {
            get;
            set;
        }

        public List<KeywordDto> Keywords
        {
            get;
            set;
        }

        protected Repeater EnetaTags;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            EnetaTags.ItemDataBound += new RepeaterItemEventHandler(EnetaTags_ItemDataBound);
        }

        void EnetaTags_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;
            var tag = e.Item.FindControl("Tag") as HtmlGenericControl;
            var data = e.Item.DataItem as DataRowView;
            if (data == null)
                return;
            if (tag == null)
                return;
            if (e.Item.ItemIndex < _tagCount - 1)
            {
                tag.InnerText = data["Tag"].ToString() + ", ";
            }
            else
            {
                tag.InnerText = data["Tag"].ToString();
            }
        }

        protected override void  OnLoad(EventArgs e)
        {
 	         base.OnLoad(e);

             if (IsPostBack)
                 return;

             if (Keywords == null)
             {
                 this.Visible = false;
             }

             
             BindKeywordsAsTags(Keywords);

        }

        private void BindKeywordsAsTags(List<KeywordDto> keywords)
        {
            var tags = ParseKeywords(keywords);
            if (tags.Rows.Count > 0)
            {
                _tagCount = tags.Rows.Count;
                EnetaTags.DataSource = tags;
                EnetaTags.DataBind();
                
            }
        }

        private DataTable ParseKeywords(List<KeywordDto> keywords)
        {
            if (keywords == null)
                return new DataTable();
            if (keywords.Count == 0)
                return new DataTable();
            var result = new DataTable();
            var tagColumnName = "Tag";
            result.Columns.Add(tagColumnName, typeof(string));
            DataRow row;
            foreach (var keyword in keywords)
            {
                row = result.NewRow();
                row[tagColumnName] = keyword.Title;
                result.Rows.Add(row);

            }
            return result;
        }

        public void Update()
        {
            BindKeywordsAsTags(Keywords);
        }
    }
}
